<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :immediate-check="false"
    >
      <CommentItem
        v-for="(item, index) in list"
        :key="index"
        :item="item"
      ></CommentItem>
    </van-list>
    <!-- 评论列表 -->
  </div>
</template>

<script>
import { getCommentsOrBack } from '@/api/article/comment.js'
import CommentItem from './CommentItem.vue'
export default {
  name: 'CommentList',
  props: {
    articleIdOrCommentId: {
      type: [String, Number, Object],
      required: true
    },
    type: {
      type: String,
      default: 'a'
    }
  },
  created() {
    this.onLoad()
  },
  components: { CommentItem },
  data() {
    return {
      list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      offset: null,
      limit: 10
    }
  },
  methods: {
    async onLoad() {
      // 异步更新数据
      try {
        const params = {
          type: this.type,
          source: this.articleIdOrCommentId.toString(),
          offset: this.offset,
          limit: this.limit
        }
        const { data: res } = await getCommentsOrBack(params)
        const { results } = res.data
        this.list.push(...results) // 获取评论列表数据
        const newVal = res.data.total_count // 评论总数
        this.$emit('input', newVal) // 传递给父组件
        this.list.length !== res.data.total_count
          ? (this.offset = res.data.last_id)
          : (this.finished = true) // 偏移量更新
      } catch (error) {
        this.$toast.fail('服务器繁忙')
      }
      this.loading = false
    }
  }
}
</script>

<style scoped lang="less">
.publish-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
}
.van-list {
  margin-bottom: 45px;
}
</style>
